package wqh.dao.impl;

import org.hibernate.Session;
import org.springframework.stereotype.Repository;
import wqh.dao.WaterDeviceDao;
import wqh.domain.WaterDevice;

import org.hibernate.query.Query;
import java.util.List;

/**
 * Created by devts on 2017/1/5.
 */
@Repository("waterDeviceDao")
public class WaterDeviceDaoImpl extends DaoImpl<WaterDevice> implements WaterDeviceDao {

    public long findIdByIpAndPort(String ip, Integer port) {
        Session session = this.getSessionFactory().getCurrentSession();
        String hql = "SELECT w.device_id FROM WaterDevice AS w where w.ip = :ip and w.port = :port";
        Query query = session.createQuery(hql);
        query.setParameter("ip",ip);
        query.setParameter("port",port);
        List result = query.getResultList();
        if(result.isEmpty()) return 0;
        return (Long)result.get(0);
    }

    @Override
    public WaterDevice findByDeviceId(long device_id) {
        Session session = this.getSessionFactory().getCurrentSession();
        String hql = "FROM WaterDevice w WHERE w.device_id = :device_id";
        Query query = session.createQuery(hql);
        query.setParameter("device_id",device_id);
        return query.list() == null ? null : (WaterDevice)query.list().get(0);
    }
}
